import os.path
import json
from flask import request,send_file
import constants
from SQLConfig import app


@app.route('/getProjectFile', methods=['Get', 'POST'])
def getProjectFile():  # put application's code here
    """
    获取患者工程文件，后端仅返回文件内容，由前端判断其是否已经配准
    """
    if request.method == 'POST':
        patientId=request.json.get("patientId")
    elif request.method == 'GET':
        patientId=request.args.get("patientId")
    patientId=str(patientId)
    projectFilePath = os.path.join(constants.patientBaseUrl, patientId, constants.projectFileName)
    if os.path.isfile(projectFilePath):
        with open(projectFilePath, encoding='utf-8') as f:
            data = f.read()
            data=json.loads(data)
            files=[]
            colors=[]
            visible=[]
            show_names=[]
            matrix=[]
            needData=list(data["stlFiles"])
           
            for i in range(len(needData)):
                files.append(needData[i]["filename"])
                colors.append(needData[i]["color"])
                visible.append(needData[i]["visible"])
                show_names.append(needData[i]["showname"])
                matrix.append(needData[i]["transform_matrix"].get("elements",[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]))
            return json.dumps({
                "success":"true",
                "files":files,
                "colors":colors,
                "visible":visible,
                "show_names":show_names,
                "rotation_axis":data["information"].get("rotationAxis",None),
                "matrix": matrix
            })
    else:
        return "wrong"

@app.route('/getBinaryFile', methods=['Get', 'POST'])
def getBinaryFile():  # put application's code here
    """
    获取患者牙颌文件，后端仅返回二进制文件内容。
    """
    if request.method == 'POST':
        patientId=request.json.get("patientId")
    elif request.method == 'GET':
        patientId=request.args.get("patientId")
    patientId=str(patientId)
    BinaryFilePath = os.path.join(constants.patientBaseUrl, patientId, constants.patientStlUrl,request.json.get("fileName"))
    if os.path.isfile(BinaryFilePath):
        return send_file(BinaryFilePath)
    else:
        return "wrong"